﻿using Newtonsoft.Json.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Support.UI;
using ToolApp.Common;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;

namespace ToolApp.EdgeRewards;

public class EdgeRewardsBase
{
    public IWebDriver? WebDriver;
    
    /// <summary>
    /// 是否移动端
    /// </summary>
    public bool IsMobile { get; set; }

    /// <summary>
    /// 最后可用积分
    /// </summary>
    public int? LastTotal { get; set; }

    public EdgeRewardsBase(bool isMobile)
    {
        IsMobile = isMobile;
        Init();
    }

    /// <summary>
    /// 初始化
    /// </summary>
    private void Init()
    {
        if (WebDriver != null)
        {
            return;
        }
        new DriverManager().SetUpDriver(new EdgeConfig());
        var options = new EdgeOptions
        {
            PageLoadTimeout = TimeSpan.FromSeconds(6000)
        };
        //options.AddArgument("--window-size=720,360");
        options.AddArgument("--disable-features=ChromeBrowserCloudManagement");
        options.AddArgument("--disable-features=EdgeQQBrowserImporter");
        if (IsMobile)
        {
            options.AddArgument("--user-agent=Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.102 Mobile Safari/537.36 EdgA/104.0.1293.70");
        }
        WebDriver = new EdgeDriver(options);
        var manage = WebDriver.Manage();
        var timeouts = manage.Timeouts();
        timeouts.PageLoad = TimeSpan.FromSeconds(6000);
        timeouts.ImplicitWait = TimeSpan.FromSeconds(10);
        //manage.Window.Minimize();
    }

    public IWebElement WaitUntilClickable(By by, float timeToWait = 100)
    {
        var btn = WebDriver!.FindElement(by);
        WaitUntil(_ => btn.Enabled, timeToWait);
        return btn;
    }

    public void WaitUntilUrl(string[] urls, float timeToWait = 100)
    {
        WaitUntil(driver =>
            !string.IsNullOrWhiteSpace(urls.FirstOrDefault(s =>
                driver.Url?.Contains(s, StringComparison.OrdinalIgnoreCase) == true)), timeToWait);
    }

    public void WaitUntil(Func<IWebDriver, bool> expression, float timeToWait = 100)
    {
        var wait = new WebDriverWait(WebDriver, TimeSpan.FromSeconds(timeToWait));
        wait.Until(expression);
    }

    public void GoToUrl(string url)
    {

    }

    public JObject GetDashboardData()
    {
        var js = (IJavaScriptExecutor)WebDriver!;
        var data = JObject.FromObject(js.ExecuteScript("return dashboard"));
        return data;
    }

    public void Quit()
    {
        WebDriver?.Quit();
    }
}